//index.js
//获取应用实例
const app = getApp()
// 调用工具类
let util = require('../../utils/util.js')

Page({
   STANDARD: 22,
  rules: [
    [18.5, 24, 28],
    [18.5, 25, 30, 35, 40],
    [18.5, 23, 25, 30]
  ],
  ruleConfig: ['偏瘦', '正常', '偏胖', '肥胖', '重度肥胖', '极重度肥胖'],
  dangerConfig: ['低（但其它疾病危险性增加）', '平均水平', '增加', '中度增加', '严重增加', '非常严重增加'],
  data: {
    array: ['中国标准', '国际标准', '亚洲标准'],
    physicalCondition: '未知',
    weightStandard: 0,
    danger: '未知',
    charLt: '<',
    userInfo: {},
    hasUserInfo: false,
    targetstep: 8000,
    userSteps: {},
    power_kcal: 0,
    sport_distance: 0,
    ground_distance: 0,
    rice_g: 0,
    hasTarget: false,
    nowstep:0,//已兑换
    showstep:0,//显示
    height:0,
    weight:0,
    jifen:0,
    BMI:0,
    actual:0,
    werun:false,
    current_step:0,
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onReady: function (e) {
  },
  onLoad: function () {
    console.log(app);
    let that = this
    app.editTabBar();

    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/stepuser',
      data: {
        uid:  app.d.userId
      },
      method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        let rest = res.data;
        
        // console.log(app);
        if(rest.status==0){
           // wx.showToast({
           //       title:'请填写正确的个人信息',
           //       icon: 'none',
           //       duration: 1000
           //   });
            // setTimeout(function () {
            wx.redirectTo({
               url: '../editinfo/editinfo',
            })
            return false;
             // }, 1000);
        }else{
          app.d.store_Id=rest.data.store_id;
          wx.setStorage({ key: "stepuser", data:rest.data })
          let heightt = rest.data.height / 100;
          let score = (rest.data.weight / (heightt * heightt)).toFixed(1);
           that.setData({ 
              targetstep: rest.data.target_step,
              nowstep: rest.data.stepnum,
              height:rest.data.height,
              weight:rest.data.weight,
              jifen:rest.data.jifen,
              actual:rest.data.actual,
              BMI:score,
           })
        }
 
      }
    }),
   that.getsports();

    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    setTimeout(function () {
      that.weightStandardCalculate();
      that.physicalConditionCalculate();
    } , 2000)
    console.log(that.data.userInfo);

  },
  retry: function () {
    var that=this
    wx.getSetting({
      success(res) {
        var resd=res.authSetting
        console.log(resd['scope.werun'])
        if(resd['scope.werun']){
              wx.showToast({
                      title: '加载中,请稍后',
                      icon:'loading',
              })
             setTimeout(function () {
                    that.getsports();
                } , 2000)
        }else{
           wx.showModal({  
             title: '提示',  
             content: '获取步数需要微信授权',  
             success: function(res) {  
                if (res.confirm) {  
                    wx.openSetting({
                      success: function (res) { 
                          console.log(res);
                          // 这里重新调用代码，比如这里的重新显示头像昵称
                          if (res.authSetting["scope.werun"]) {
                               that.getsports();
                          }else{
                                wx.showToast({
                                   title:'请确认微信运动授权',
                                   icon: 'none',
                                   duration: 2000
                               });
                          }
                       }
                      });
                } else if (res.cancel) {  
                  console.log('用户点击取消')  
                }  
              }  
           })  
        }
      }
    })




  },
  getsports:function(){
    var that=this
    wx.login({
      success: function (res) {
        let code = res.code
        that.setData({ code: code })
        wx.getWeRunData({//解密微信运动
          success(res) {
            const wRunEncryptedData = res.encryptedData
            that.setData({ 
              encryptedData: wRunEncryptedData,
              iv: res.iv,
              now_time: util.haveSomeMinutesTime()
            })
            that.get3rdSession()//解密请求函数
          }
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  get3rdSession: function (callback) {
    let that = this
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/getsessionkey',
      data: {
        code: this.data.code
      },
      method: 'post', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        let rest = res.data;
        // let sessionKey = res.data.replace(/\s+/g, "") //很重要去除空格 session_key标准24位
        that.setData({ 
          sessionKey: rest.session_key,
          openid: rest.openid 
       })
        that.decodeUserInfo(callback)
      }
    })
  },
  // 解析数据
  decodeUserInfo: function (callback) {
    let that = this
    // console.log(that.data.userInfo)
    wx.request({
      url: app.d.ceshiUrl + '/Api/Login/decrypt',
      data: {
        encryptedData: that.data.encryptedData,
        iv: that.data.iv,
        session: that.data.sessionKey,
        nickname: that.data.userInfo.nickName,
        head_img: that.data.userInfo.avatarUrl,
        target_step: that.data.targetstep,
        openid: that.data.userInfo.openid
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        let todayStep = res.data.replace(" ", "");
        // json 字符串转json
        if (typeof todayStep != 'object') {
          todayStep = todayStep.replace(/\ufeff/g, "");//重点
          let jj = JSON.parse(todayStep);
          todayStep = jj;
        }
        let now_step = todayStep.stepInfoList[30].step
        let bufu   =that.data.height*0.45 //步幅
        let sport_distance = now_step *bufu* 0.00001 //行走的里程
        let power_kcal = that.data.weight*sport_distance * 1.036 //消耗的大卡
        let ground_distance = sport_distance*1000 / 200 //相当于几圈200米操场
        let rice_g = power_kcal * 1.16 //相当于消耗几克米饭
        // 保存用户近31天步数
        that.setData({
          userSteps: todayStep.stepInfoList,
          power_kcal: power_kcal.toFixed(1),
          sport_distance: sport_distance.toFixed(2),
          ground_distance: ground_distance.toFixed(1),
          rice_g: rice_g.toFixed(1),
          current_step:todayStep.stepInfoList[30].step
          // userlog: todayStep.userinfo,
          // step_day: todayStep.step_day,
          // step_month: todayStep.step_month,
        });
        console.log(that.data.sport_distance);
        console.log(that.data.ground_distance);
     
        // 储存基本信息
        wx.setStorage({ key: "openid", data: that.data.openid })
        wx.setStorageSync("step", todayStep.stepInfoList[30].step) 
        wx.setStorageSync("stepk", power_kcal.toFixed(1)) 
        // 判断今日是否达标
        if (now_step > that.data.targetstep) {
          that.setData({ hasTarget: true })
        }
        console.log(todayStep)
        // 渲染canvas
          that.printCanvas();
      }
    })
  },
  printCanvas: function (e) {
    let that = this
    let query = wx.createSelectorQuery();
    query.select('#canvas-print').boundingClientRect()
    query.exec(function (res) {
      //res就是 所有标签为mjltest的元素的信息 的数组
      //取宽度
      let midwidth = res[0].width / 2
      let midheight = res[0].height / 2
      //创建并返回绘图上下文context对象。
      let ctx = wx.createCanvasContext('canvasCircle')
      //今天步数
      let nowstep = that.data.userSteps[30].step
      let now_step=that.data.now_step
      // var nowstep=9000
      //目标步数
      let targetstep = that.data.targetstep
      that.setData({
        targetstep: targetstep,
        showstep:nowstep-that.data.nowstep
      })
      if(nowstep > targetstep){//大于
          if(nowstep<16000){
            var flag=2;
            var x = nowstep / 16000 //当前所走步数占目标步数的比
          }else if(16000<nowstep<24000){
            var flag=3;
            var x = nowstep / 24000 //当前所走步数占目标步数的比
          }else{
            var flag=4;
            var x =1;
          }
      }else{//小于
        var flag=1;
        var x = nowstep / targetstep //当前所走步数占目标步数的比
      }
      // let x = nowstep / targetstep //当前所走步数占目标步数的比
      // if (nowstep > targetstep) {
      //   x = 1
      // }

      let start = 1.5 * Math.PI
      let end = start + 2 * Math.PI * x
      ctx.setLineCap('round')
      ctx.setTextAlign('center')

      if(flag==1){
        ctx.beginPath()
        ctx.setLineWidth(35)
        ctx.setStrokeStyle('#D4E8ED')//圈底色
        ctx.arc(midwidth, midheight, midheight * 0.7, 0, 2 * Math.PI, false)
        ctx.stroke()

        ctx.beginPath()
        ctx.arc(midwidth, midheight, midheight * 0.62, 0, 2 * Math.PI)
        ctx.setFillStyle('white')
        ctx.fill()

        ctx.beginPath()
        ctx.setLineWidth(30)
        ctx.setStrokeStyle('#97E4E7')//圈顶色
        ctx.arc(midwidth, midheight, midheight * 0.72, start, end, false)
        ctx.stroke()

      }else if(flag==2){
        ctx.beginPath()
        ctx.setLineWidth(35)
        ctx.setStrokeStyle('#97E4E7')//圈底色
        ctx.arc(midwidth, midheight, midheight * 0.7, 0, 2 * Math.PI, false)
        ctx.stroke()

        ctx.beginPath()
        ctx.arc(midwidth, midheight, midheight * 0.62, 0, 2 * Math.PI)
        ctx.setFillStyle('white')
        ctx.fill()

        ctx.beginPath()
        ctx.setLineWidth(30)
        ctx.setStrokeStyle('#CDBA96')//圈顶色
        ctx.arc(midwidth, midheight, midheight * 0.72, start, end, false)
        ctx.stroke()

      }else if(flag==3){
        ctx.beginPath()
        ctx.setLineWidth(35)
        ctx.setStrokeStyle('#CDBA96')//圈底色
        ctx.arc(midwidth, midheight, midheight * 0.7, 0, 2 * Math.PI, false)
        ctx.stroke()

        ctx.beginPath()
        ctx.arc(midwidth, midheight, midheight * 0.62, 0, 2 * Math.PI)
        ctx.setFillStyle('white')
        ctx.fill()

        ctx.beginPath()
        ctx.setLineWidth(30)
        ctx.setStrokeStyle('#EE7942')//圈顶色
        ctx.arc(midwidth, midheight, midheight * 0.72, start, end, false)
        ctx.stroke()
        
      }else if(flag==4){
        ctx.beginPath()
        ctx.setLineWidth(35)
        ctx.setStrokeStyle('#EE7942')//圈底色
        ctx.arc(midwidth, midheight, midheight * 0.7, 0, 2 * Math.PI, false)
        ctx.stroke()

        ctx.beginPath()
        ctx.arc(midwidth, midheight, midheight * 0.62, 0, 2 * Math.PI)
        ctx.setFillStyle('white')
        ctx.fill()

        ctx.beginPath()
        ctx.setLineWidth(30)
        ctx.setStrokeStyle('#EE3B3B')//圈顶色
        ctx.arc(midwidth, midheight, midheight * 0.72, start, end, false)
        ctx.stroke()
      }else{

      }
      ctx.beginPath()
      ctx.setFillStyle('#444444')
      ctx.setFontSize(10)
      ctx.fillText('今日步数', midwidth, midheight-40)

      ctx.beginPath()
      ctx.setFillStyle('#3E4858')
      ctx.setFontSize(38)
      ctx.fillText(nowstep, midwidth, midheight)

      ctx.beginPath()
      ctx.setFillStyle('#444444')
      ctx.setFontSize(10)
      ctx.fillText('点击兑换', midwidth, midheight + 30)

      ctx.beginPath()
      ctx.setFillStyle('#444444')
      ctx.setFontSize(10)
      ctx.fillText('可兑换'+that.data.showstep+'步', midwidth, midheight + 50)
      ctx.draw()
    })
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  charts: function (e) {
    wx.navigateTo({
      url: '../honors/honors?',
    })
  },
  target: function (e) {
    wx.navigateTo({
      url: '../editinfo/editinfo',
    })
  },
  modalcnt:function(){
    var that=this;  
    var sjstep=that.data.userSteps[30].step-that.data.nowstep;
    var jifen=parseFloat(sjstep*0.0006).toFixed(2);
    if(sjstep<500){
       wx.showToast({
         title:'加油！大于500步才能兑换积分',
         icon: 'none',
        duration: 1500
       });
    }else{
    wx.showModal({  
            // title: '提示',  
        content: '兑换'+sjstep+'步为'+jifen+'积分',  
        success: function(res) {  
           if (res.confirm) {  
             wx.request({
                url: app.d.ceshiUrl + '/Api/Step/step_exchange',
                data: {
                  current_step:that.data.current_step,
                  step: sjstep,
                  uid: app.d.userId
                },
                method: 'POST',
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: function (res) {
                   console.log(res);
                      that.setData({
                        nowstep: res.data.stepnum,
                        actual:res.data.actual,
                        showstep:0,
                      })   
                      that.printCanvas(); 
                 }
              }) 
           } else if (res.cancel) {  
              console.log('用户点击取消')  
           }  
        }  
    })  
    }
  },
    //计算标准体重
  weightStandardCalculate: function () {
    let weight = 0;
    let height = this.data.height / 100;
    weight = (this.STANDARD * (height * height)).toFixed(1);
    this.setData({
      weightStandard: weight
    })
  },
  //身体状况计算
  physicalConditionCalculate: function () {
    let rule = this.rules[0];
    let value = 0;
    let score = this.data.BMI;
    let length = rule.length;
    if (score >= rule[length - 1]) {
      value = length;
    } else {
      for (let length = rule.length, i = length; i >= 1; --i) {
          if (score < rule[i] && score >= rule[i - 1])
            value = i;
        }
    }
    this.setData({
      physicalCondition: this.ruleConfig[value]
    })

    this.setData({
      danger: this.dangerConfig[value]
    })
  },
  onShareAppMessage: function (res) {
      var user=this.data.userInfo;
    return {
      title:'我正在用云康医护步数兑换商品，快来跟我一起抢！',
      path: "/pages/FirstPage/FirstPage?flag=1&f_uid=" + app.d.userId,
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    }
  },  

})
